package com.controller;

import com.dto.Result;
import com.entity.PropertyMonthlyFinance;
import com.service.PropertyMonthlyFinanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/property/finance")
public class PropertyMonthlyFinanceController {

    @Autowired
    private PropertyMonthlyFinanceService propertyMonthlyFinanceService;


    @PostMapping
    public void create(@RequestBody PropertyMonthlyFinance propertyMonthlyFinance) {
        propertyMonthlyFinanceService.save(propertyMonthlyFinance);

    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        propertyMonthlyFinanceService.deleteById(id);
    }

    @PutMapping("/{id}")
    public PropertyMonthlyFinance update(@PathVariable Integer id, @RequestBody PropertyMonthlyFinance propertyMonthlyFinance) {
        propertyMonthlyFinance.setId(id);
        return propertyMonthlyFinanceService.update(propertyMonthlyFinance);
    }
    
    @GetMapping("/{id}")
    public PropertyMonthlyFinance detail(@PathVariable Integer id) {
        return propertyMonthlyFinanceService.findById(id);
    }

    /**
     * 获取所有物业月度财务信息
     * @return 结果
     */
    @GetMapping("/list")
    public List<PropertyMonthlyFinance> list() {
        return propertyMonthlyFinanceService.findAll();
    }

    /**
     * 分页查询物业月度财务信息
     * @param pageNum 页码（从1开始）
     * @param pageSize 每页大小
     * @param projectName 项目名称（模糊查询）
     * @return 结果
     */
    @GetMapping("/page")
    public Page<PropertyMonthlyFinance> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String projectName) {
        
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<PropertyMonthlyFinance> page;
        
        if (projectName != null && !projectName.isEmpty()) {
            page = propertyMonthlyFinanceService.findByProjectNameContaining(projectName, pageable);
        } else {
            page = propertyMonthlyFinanceService.findAll(pageable);
        }
        
        return page;
    }
}